package com.newworld.dmsapp2.activity.visit;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.newworld.dmsapp2.BaseActivity;
import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.ui.view.CustomDialog;
import com.newworld.dmsapp2.ui.view.CustomLoadingDialog;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;

/**
 * 
 * @author long 回访详情的界面
 */
public class VisitDetailActivity extends BaseActivity implements
		OnClickListener {
	private TextView ownerPhoneTv, ownerNameTv;
	private Button finishVisitBtn;
	private TextView titleCenterTv;
	private EditText visitRecordEdit;
	private LinearLayout leftLinLayout;
	private User user;
	
	private Intent intent;
	private Bundle bundle;
	private String functioncode;
	private String repairId;
	private String sessionId;
	private String realName;
	private String phoneNum;
	private CustomLoadingDialog uploadingdialog;

	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case Config.HANDLER_MSG_REVISIT_SUCCESS:

				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}

				 bundle.putString(Config.FUNCTIONTITLENAME, Config.FUNCTIONTITLENAME_REVISIT);
				finish();
				Toast.makeText(VisitDetailActivity.this,
						(String) msg.obj, Toast.LENGTH_SHORT);
				break;

			case Config.HANDLER_MSG_FAIL:
				if (uploadingdialog != null) {
					if (uploadingdialog.isShowing()) {
						uploadingdialog.dismiss();
					} else {
						uploadingdialog.show();
					}
				}
				showShortToast((String) msg.obj);
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_visit_detail);
		initData();
		initViews();
		initEvents();
	}

	private void initData() {
		intent = getIntent();
		bundle = intent.getExtras();
		functioncode = bundle.getString(Config.FUNCTIONCODE);
		repairId = bundle.getString(Config.REPAIRID);
		realName = bundle.getString(Config.REALNAME);
		phoneNum = bundle.getString(Config.PHONENUM);
		user = SingleSample.getInstance(this).getUser();
		User user = SingleSample.getInstance(VisitDetailActivity.this)
				.getUser();
		if (null != user) {
			if (null != user.getSessionId()
					&& !user.getSessionId().equals("")) {
				sessionId = user.getSessionId();
			}
		}
	}
	
	@Override
	protected void initViews() {
		// TODO Auto-generated method stub
		titleCenterTv = (TextView) findViewById(R.id.titlebar_left_center_title);
		leftLinLayout = (LinearLayout) findViewById(R.id.titlebar_left_left_layout);
		ownerNameTv = (TextView) findViewById(R.id.tv_houser_owner);
		ownerPhoneTv = (TextView) findViewById(R.id.tv_owner_phone);
		visitRecordEdit = (EditText) findViewById(R.id.edtTxt_visit_record);
		finishVisitBtn = (Button) findViewById(R.id.btn_finish_visit);
		ownerNameTv.setText(realName);
		ownerPhoneTv.setText(phoneNum);
		uploadingdialog = new CustomLoadingDialog(VisitDetailActivity.this,
				"正在上传...");

	}

	@Override
	protected void initEvents() {
		// TODO Auto-generated method stub
		if(functioncode.equals(Config.FUNCTION_PMREVISIT)){
			titleCenterTv.setText("终止回访详情");	
			finishVisitBtn.setText("终止回访");
		}else{
			titleCenterTv.setText("回访详情");
		}
		ownerPhoneTv.setOnClickListener(this);
		leftLinLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				onBackPressed();
			}
		});
		finishVisitBtn.setOnClickListener(this);
		// 给业主电话添加下划线
		ownerPhoneTv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
		ownerPhoneTv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
	}

	

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		//case R.id.titlebar_left_left_layout:
			// TODO Auto-generated method stub
			
			//break;
		case R.id.tv_owner_phone:
			// TODO Auto-generated method stub
			Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
					+ ownerPhoneTv.getText().toString()));
			startActivity(i);
			break;
		case R.id.btn_finish_visit:
			if (null == visitRecordEdit.getText().toString()
					|| visitRecordEdit.getText().toString().equals("")) {
				Toast.makeText(VisitDetailActivity.this, "回访记录不能为空",
						Toast.LENGTH_SHORT).show();
			} else {
				final CustomDialog dialog = new CustomDialog(
						VisitDetailActivity.this);
				if(functioncode.equals(Config.FUNCTION_PMREVISIT)){
					dialog.setTitle("终止回访");
					dialog.setDetial("是否终止回访？");
				}else{
					dialog.setTitle("回访");
					dialog.setDetial("是否完成回访？");
				}
				
				dialog.setLeftOnClick(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
					}
				});
				dialog.show();
				dialog.setRightOnClick(new OnClickListener() {
					@Override
					public void onClick(View v) {
						dialog.dismiss();
						if (uploadingdialog.isShowing()) {
							uploadingdialog.dismiss();
						} else {
							uploadingdialog.show();
						}
						new Thread(postReVisitRun).start();
						
					}
				});
				dialog.show();
			}
			break;
		}
	}

	Runnable postReVisitRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			postReVisit();
		}
	};
	private String message;

	// 请求完成回访、终止回访
	private void postReVisit() {
		if (Tool.isNetworkAvailable(VisitDetailActivity.this)) {
			try {
				String urlstr;
				String result = null;
				Map<String, String> map = new HashMap<String, String>();
				if(functioncode.equals(Config.FUNCTION_PMREVISIT)){
					urlstr = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_REAL_PMSTOP)
									.get(0).getFunctionUrl();
					map.put("functionCode",
							Config.FUNCTION_REAL_PMSTOP);
					//map.put("revisitRecord", visitRecordEdit.getText().toString());
				}else{
					urlstr = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.fUNCTION_REAL_REVISITTASKCOMPLETE)
									.get(0).getFunctionUrl();
					map.put("functionCode",
							Config.fUNCTION_REAL_REVISITTASKCOMPLETE);
					//map.put("revisitRecord", visitRecordEdit.getText().toString());
				}
				
				map.put("revisitRecord", visitRecordEdit.getText().toString());
				map.put("repairId", repairId);
				
				result = HttpUtil.postRequestSe(urlstr, map, sessionId);
				Log.e("完成回访的result", result);
				message = new JSONObject(result).getString("message");
				String flag = new JSONObject(result).getString("flag");
				if (flag.equals(Config.CONNECT_SUCCESS2)) {
					mHandler.obtainMessage(Config.HANDLER_MSG_REVISIT_SUCCESS,
							message).sendToTarget();// 通知主线程数据发送成功

				} else {
					mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
							.sendToTarget();
				}// 通知主线程数据发送成功}

			} catch (Exception e) {
				Log.e("ServiceScheduleActivity", "json数据获取报错");
				mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
						.sendToTarget();
				e.printStackTrace();
			}

		} else {
			mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, "请设置网络")
					.sendToTarget();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) { // 监控/拦截/屏蔽返回键
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
